import React, { Component } from 'react';
import {
    StyleSheet,
    View,
    Text,
    Image,
    TouchableOpacity,
    FlatList,
    SafeAreaView,
    Alert
} from 'react-native';
import { RRCLoading, RRCToast, RRCAlert } from 'react-native-overlayer';
import CheckBox from 'react-native-check-box';
import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import BaseComponent from '../component/BaseComponent';
import HttpUtil from '../util/HttpUtil';
import { NavigationEvents } from 'react-navigation';
import { read, stat } from 'react-native-fs';
import { queryInventoryPage, InventoryTableName, update, queryByConditions, InventoryDetailTableName,updateList } from '../util/RealmUtil';

let pageNo = 1; //当前第几页
let totalPage = 0; //总的页数

const buttons = [
    { text: '取消', style: { color: '#999', fontWeight: 'bold' } },
    { text: '确定', style: { color: '#999', fontWeight: 'bold' } }
];
let alertFlag = '';
export default class Inventory extends BaseComponent {

    constructor(props) {
        super(props);
        this.state = {
            inventoryCount: 0,
            noInventoryCount: 0,
            selectedInventory: [],
            data: [],
            showFoot: 0,
            curFetchState: 1
        }
    }

    componentDidMount() {
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
            loadingTextStyle: {}
        })
        RRCLoading.show();
        this.fetchData(pageNo, this.state.curFetchState);
    }

    componentWillUnmount() {
        if (alertFlag) {
            RRCAlert.hide(alertFlag);
        }
    }
    fetchDataFromLocal = (pageNo, state) => {
        queryInventoryPage('status', state, pageNo, 10).then((result) => {
            console.log(JSON.stringify(result));
            RRCLoading.hide();
            this.setCount(result.inventoryCount, result.noInventoryCount);
            let foot = 0;
            totalPage = result.detailList.pages; //获取总页数
            if (pageNo >= totalPage) {
                foot = 1;//listView底部显示没有更多数据了
            }
            if (pageNo == 1) {
                this.setState({
                    data: [],
                });
            }
            this.setState({
                data: [...this.state.data, ...result.detailList.records],
                showFoot: foot,

            });

        }).catch((error) => {
            console.log(error);
            RRCLoading.hide();
            RRCToast.show('系统异常', 1, 7000);
        })
    }
    fetchData = (pageNo, state) => {
        if (global.variables.useMode == 1) {
            this.fetchDataFromLocal(pageNo, state);
        } else {
            this.fetchDataFromServe(pageNo, state);
        }
    }
    fetchDataFromServe = (pageNo, state) => {
        let params = {
            pageNum: pageNo,
            pageSize: 10,
            listType: state
        }
        console.log(params)
        HttpUtil.post('inventoryListData', params)
            .then(result => {
                if (result.httpCode == 200) {
                    console.log(JSON.stringify(result));
                    this.setCount(result.data.inventoryCount, result.data.noInventoryCount);
                    let foot = 0;
                    totalPage = result.data.detailList.pages; //获取总页数
                    //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
                    if (pageNo >= totalPage) {
                        foot = 1;//listView底部显示没有更多数据了
                    }
                    if (pageNo == 1) {
                        this.setState({
                            data: [],
                        });
                    }
                    this.setState({
                        data: [...this.state.data, ...result.data.detailList.records],
                        showFoot: foot,

                    });
                    RRCLoading.hide();
                } else {
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 7000);
                }
            })
            .catch(error => {
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 7000);
            })
    }

    _onEndReached() {
        //console.log('pageNo:' + pageNo + ' totalPage:' + totalPage);
        //如果是正在加载中或没有更多数据了，则返回
        if (this.state.showFoot != 0) {
            return;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if ((pageNo != 1) && (pageNo >= totalPage)) {
            return;
        } else {
            pageNo++;
        }
        //底部显示正在加载更多数据
        this.setState({ showFoot: 2 });
        //获取数据
        this.fetchData(pageNo, this.state.curFetchState);
    }

    detail = (id) => {
        this.props.navigation.navigate('InventoryDetail', {
            id: id,
            callBack: () => {
                this.setState({
                    data: [],
                });
                pageNo = 1;
                this.fetchData(pageNo, this.state.curFetchState);
            }
        });
    }

    _renderFooter() {
        if (this.state.showFoot === 1) {
            return (
                <View style={{ height: getPixel(30), alignItems: 'center', marginTop: getPixel(5), justifyContent: 'flex-start' }}>
                    <Text style={{ color: '#999999', fontSize: getPixel(14), marginBottom: getPixel(5) }}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if (this.state.showFoot === 2) {
            return (
                <View style={{ height: getPixel(30), alignItems: 'center', marginTop: getPixel(5), justifyContent: 'flex-start' }}>
                    <Text style={{ color: '#999999' }}>正在加载更多数据...</Text>
                </View>
            );
        } else if (this.state.showFoot === 0) {
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    renderState(id, state) {
        if (state == 1) {
            // return <TouchableOpacity onPress={() => this.detail(id)}><Text style={styles.stateStart}>开始盘点</Text></TouchableOpacity>
            return <Text style={styles.stateStart}>未完成</Text>
        } else if (state == 2) {
            return <Text style={styles.stateFinish}>已完成</Text>
        }
    }
    detailView(id, state) {
        if (state == 1) {
            this.props.navigation.navigate('InventoryDetail', {
                id: id,
                callBack: () => {
                    this.setState({
                        data: [],
                    });
                    pageNo = 1;
                    this.fetchData(pageNo, this.state.curFetchState);
                }
            });
        } else if (state == 2) {
            this.props.navigation.navigate('ViewInventoryDetail', {
                id: id,
                callBack: () => {
                    this.setState({
                        data: [],
                    });
                    pageNo = 1;
                    this.fetchData(pageNo, this.state.curFetchState);
                }
            });
        }
    }

    finishInventory(id, executeTime) {
        Alert.alert(
            "提示",
            "确定要完成盘点吗？",
            [
                {
                    text: "取消",
                    onPress: () => console.log("Cancel Pressed"),
                    style: "cancel"
                },
                {
                    text: "确定", onPress: () => {
                        RRCLoading.setLoadingOptions({
                            text: '请稍候',
                            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
                            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
                            loadingTextStyle: {}
                        })
                        RRCLoading.show();
                        if (global.variables.useMode == 1) {
                            this.finishInventoryFromLocal(id, executeTime);
                        } else {
                            this.finishInventoryFromServe(id, executeTime);
                        }
                    }
                }
            ]
        );
    }
    // 本地完成盘点
    async finishInventoryFromLocal(id, executeTime) {
        let loss = 0;
        // 查询未盘点的资产数量
        await queryByConditions(InventoryDetailTableName, `inventoryId='${id}' and status=1`).then(async result => {
            if(result){
                loss=result.length;
                let lossList = [];
                result.forEach(item => {
                    let lossItem = item;
                    lossItem.status = 4;
                    lossList.push(item);
                });
                await updateList(InventoryDetailTableName,lossList);
            }
        }).catch(error => {
            console.log(error);
        });
        let args = {
            id_: id,
            executeTime: executeTime,
            loss:loss,
            status: 2,
            noInventoryCount: 0,
        }
        console.log(args)
        update(InventoryTableName, args).then(result => {
            RRCLoading.hide();
            RRCToast.show('保存成功', 2, 3000);
            pageNo = 1;
            this.fetchData(pageNo, this.state.curFetchState);
        }).catch(error => {
            console.log(error);
            RRCLoading.hide();
            RRCToast.show('系统异常', 1, 7000);
        })
    }
    // 服务器完成盘点
    finishInventoryFromServe(id, executeTime) {
        let args = {
            id: id,
            executeTime: executeTime,
        }
        console.log(args)
        HttpUtil.post('finishInventory', args)
            .then(result => {
                if (result.httpCode == 200) {
                    RRCLoading.hide();
                    RRCToast.show('保存成功', 2, 3000);
                    pageNo = 1;
                    this.fetchData(pageNo, this.state.curFetchState);
                } else {
                    RRCLoading.hide();
                    RRCToast.show('系统异常', 1, 7000);
                }
            })
            .catch(error => {
                //console.log(error);
                RRCLoading.hide();
                RRCToast.show('系统异常', 1, 3000);
            })
    }

    renderCheck(id, source) {
        if (source == 2) {
            return (
                <CheckBox
                    style={{ flex: 1, width: getPixel(20), height: getPixel(40), justifyContent: 'flex-start', paddingTop: getPixel(10) }}
                    unCheckedImage={<Image source={require('../images/unchecked.png')} style={{ resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} />}
                    checkedImage={<Image source={require('../images/checked.png')} style={{ resizeMode: 'contain', width: getPixel(20), height: getPixel(20), }} />}
                    onClick={() => {
                        let selected = Array.from(this.state.selectedInventory);
                        if (selected.includes(id)) {
                            selected.splice(selected.findIndex(i => i === id), 1)
                        } else {
                            selected.push(id);
                        }
                        this.setState({
                            selectedInventory: selected,
                        })
                    }}
                    isChecked={this.state.selectedInventory.includes(id)}
                    rightTextStyle={{ color: '#999' }}
                />
            )
        }
    }

    renderItem(item) {
        return (
            <TouchableOpacity onPress={() => this.detailView(item.id_, item.status)}>
                <View key={item.id} style={{ paddingLeft: getPixel(15), paddingRight: getPixel(15), paddingBottom: getPixel(20), paddingTop: getPixel(10), backgroundColor: '#FFF', marginBottom: getPixel(10) }}>
                    <View style={styles.title}>
                        <View style={{ marginTop: getPixel(2) }}>
                            {this.renderCheck(item.id_, item.source)}
                        </View>
                        <View style={{ marginLeft: getPixel(10) }}>
                            <Text style={item.source == 2 ? [styles.titleText, { width: getScreenWidth() - getPixel(145), }] : styles.titleText}>{item.inventorySheetName}</Text>
                        </View>
                        <View style={{ width: getPixel(95), alignItems: 'center' }}>
                            {this.renderState(item.id_, item.status)}
                        </View>
                    </View>
                    <View style={styles.info}>
                        <View style={styles.infoText}>
                            <Text style={styles.infoTextTable}>
                                创建人：{item.createName}
                            </Text>
                            <Text style={[styles.infoTextTable, { marginLeft: getPixel(10) }]}>
                                盘点总数：{item.totalCount}
                            </Text>
                        </View>
                        <View style={styles.infoText}>
                            <Text style={styles.infoTextTable}>
                                创建日期：{item.createTimeString}
                            </Text>
                            <Text style={[styles.infoTextTable, { marginLeft: getPixel(10) }]}>
                                完成日期：{item.endTimeString}
                            </Text>
                        </View>
                        <View style={styles.infoText}>
                            <Text style={styles.infoTextTable}>
                                区域位置：{item.roomName}
                            </Text>
                        </View>
                        <View style={styles.detail}>
                            <View style={styles.detailBox}>
                                <Text style={[styles.detailNum, { color: '#4A69DD' }]}>{item.noInventoryCount}</Text>
                                <Text style={styles.detailName}>待盘点</Text>
                            </View>
                            <View style={styles.detailBox}>
                                <Text style={styles.detailNum}>{item.normal}</Text>
                                <Text style={styles.detailName}>已盘点</Text>
                            </View>
                            <View style={styles.detailBox}>
                                <Text style={styles.detailNum}>{item.over}</Text>
                                <Text style={styles.detailName}>盘盈</Text>
                            </View>
                            <View style={[styles.detailBox, { marginRight: getPixel(0) }]}>
                                <Text style={styles.detailNum}>{item.loss}</Text>
                                <Text style={styles.detailName}>盘亏</Text>
                            </View>
                        </View>
                        {item.status == 1 ? <TouchableOpacity onPress={() => this.finishInventory(item.id_, item.executeTime)} style={{ height: getPixel(30), alignItems: 'center', backgroundColor: '#4A69DD', borderRadius: getPixel(10), }}>
                            <Text style={{ padding: getPixel(4), paddingLeft: getPixel(8), paddingRight: getPixel(8), color: '#FFF', fontSize: getPixel(16), }}>完成盘点</Text>
                        </TouchableOpacity> : null}
                    </View>
                </View>
            </TouchableOpacity>
        )
    }

    onBackClicked = () => {
        pageNo = 1;
        this.props.navigation.navigate('Main');
        this.props.navigation.state.params.callBack();
        return true;
    }

    back = () => {
        pageNo = 1;
        this.props.navigation.navigate('Main');
        this.props.navigation.state.params.callBack();
    }

    setCount = (inventoryCount, noInventoryCount) => {
        this.setState({
            inventoryCount: inventoryCount,
            noInventoryCount: noInventoryCount,
        })
    }

    setSelected = (selected) => {
        this.setState({
            selectedInventory: selected,
        })
    }

    delete = () => {
        //console.log(this.state.selectedInventory);
        if (this.state.selectedInventory.length <= 0) {
            RRCToast.show('请选择要删除的盘点单', 2, 3000);
            return;
        }
        alertFlag = RRCAlert.alert('确定删除', '确定您要删除选择的盘点单？', buttons, (index) => {
            if (index === 1) {
                RRCLoading.setLoadingOptions({
                    text: '请稍候',
                    loadingBackgroundColor: 'rgba(0,0,0,0.0)',
                    loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
                    loadingTextStyle: {}
                })
                RRCLoading.show();
                HttpUtil.post('delInventory', this.state.selectedInventory)
                    .then(result => {
                        if (result.httpCode == 200) {
                            this.setState({
                                selectedInventory: [],
                            })
                            pageNo = 1;
                            this.fetchData(pageNo, this.state.curFetchState);
                            RRCLoading.hide();
                            RRCToast.show('删除成功', 2, 3000);

                        } else {
                            RRCLoading.hide();
                            RRCToast.show('系统异常', 1, 3000);
                        }
                    })
                    .catch(error => {
                        //console.log(error);
                        RRCLoading.hide();
                        RRCToast.show('系统异常', 1, 3000);
                    })
            }
        });
    }

    add = () => {
        this.props.navigation.navigate('AddInventory', {
            callBack: () => {
                pageNo = 1;
                this.fetchData(pageNo, this.state.curFetchState);
            }
        });
    }
    changeTab = (state) => {
        this.setState({
            curFetchState: state
        })
        RRCLoading.setLoadingOptions({
            text: '加载中',
            loadingBackgroundColor: 'rgba(0,0,0,0.0)',
            loadingViewStyle: { backgroundColor: 'rgba(0,0,0,0.8)' },
            loadingTextStyle: {}
        })
        RRCLoading.show();
        pageNo = 1;
        this.fetchData(pageNo, state);
    }

    render() {
        return (
            <SafeAreaView style={styles.container}>
                <NavigationEvents onDidBlur={() => this.componentWillUnmount()} />
                <View style={styles.header}>
                    <View style={{ width: getPixel(40), justifyContent: 'center', alignItems: 'center' }}>
                        <TouchableOpacity onPress={() => this.back()}>
                            <Image source={require('../images/back.png')} style={{ resizeMode: 'contain', width: getPixel(25), height: getPixel(25) }} />
                        </TouchableOpacity>
                    </View>

                    <View style={{ width: getScreenWidth() - getPixel(80), justifyContent: 'center', alignItems: 'center' }}>
                        <Text style={{ fontSize: getPixel(17), color: '#333' }}>资产盘点</Text>
                    </View>
                    <View style={{ width: getPixel(40), justifyContent: 'center', alignItems: 'center' }}>
                    </View>
                </View>
                <View>
                    <View style={{ flexDirection: 'row', height: getPixel(50), backgroundColor: '#FFF', justifyContent: 'center', alignItems: 'center' }}>
                        <View style={[styles.statistics, { width: getScreenWidth() / 2, height: getPixel(50), borderBottomWidth: 1, borderBottomColor: this.state.curFetchState == 1 ? '#4A69DD' : '#fff' }]}>
                            <TouchableOpacity onPress={() => this.changeTab(1)} style={[styles.statistics, { borderRightWidth: getPixel(1), borderRightColor: '#D3D3D3', }]}>
                                <Text style={{ fontSize: getPixel(16), color: '#666', }}>待盘点</Text>
                                <Text style={{ fontSize: getPixel(14), backgroundColor: '#4A69DD', borderRadius: getPixel(10), paddingLeft: getPixel(5), paddingRight: getPixel(5), marginLeft: getPixel(10), color: '#fff' }}>{this.state.noInventoryCount}</Text>
                            </TouchableOpacity>
                        </View>
                        <View style={[styles.statistics, { width: getScreenWidth() / 2, height: getPixel(50), borderBottomWidth: 1, borderBottomColor: this.state.curFetchState == 2 ? '#4A69DD' : '#fff' }]}>
                            <TouchableOpacity onPress={() => this.changeTab(2)} style={styles.statistics}>
                                <Text style={{ fontSize: getPixel(16), color: '#666' }}>已盘点</Text>
                                <Text style={{ fontSize: getPixel(14), backgroundColor: '#FFAA2E', borderRadius: getPixel(10), paddingLeft: getPixel(5), paddingRight: getPixel(5), marginLeft: getPixel(10), color: '#fff' }}>{this.state.inventoryCount}</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                </View>
                {/* <InventoryList navigation={ this.props.navigation } setCount={this.setCount} setSelected={this.setSelected} /> */}
                <FlatList
                    style={{ backgroundColor: '#F5F5F5', marginTop: getPixel(10) }}
                    data={this.state.data}
                    renderItem={({ item }) => this.renderItem(item)}
                    keyExtractor={(item, index) => index.toString()}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={1}
                    ListFooterComponent={this._renderFooter.bind(this)}
                >
                </FlatList>
                {global.variables.useMode == 1 ? null :
                    <View style={styles.buttonGroup}>
                        <TouchableOpacity onPress={() => this.delete()}>
                            <View style={styles.buttonDel}>
                                <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>删除</Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.add()}>
                            <View style={styles.buttonAdd}>
                                <Text style={{ color: '#FFFFFF', textAlign: 'center', fontSize: getPixel(16), lineHeight: getPixel(40) }}>新增</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                }
            </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5F5F5',
    },
    title: {
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#EEE',
        borderBottomWidth: getPixel(1),
        paddingBottom: getPixel(10),
    },
    titleText: {
        fontSize: getPixel(16),
        color: '#333',
        width: getScreenWidth() - getPixel(125),
    },
    stateStart: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        // backgroundColor: '#FFAA2E',
        color: '#4A69DD',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    stateFinish: {
        fontSize: getPixel(14),
        padding: getPixel(4),
        // backgroundColor: '#4A69DD',
        color: '#FFAA2E',
        borderRadius: getPixel(5),
        paddingLeft: getPixel(8),
        paddingRight: getPixel(8),
    },
    info: {
        justifyContent: 'center',
        marginTop: getPixel(10),
    },
    infoText: {
        flexDirection: 'row',
        alignItems: 'center',
        height: getPixel(30),
    },
    infoTextTable: {
        fontSize: getPixel(14),
        color: '#999',
        width: getScreenWidth() / 2,
    },
    detail: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    detailBox: {
        width: getScreenWidth() / 4 - getPixel(10),
        height: getScreenWidth() / 4 - getPixel(10),
        backgroundColor: '#FAFAFA',
        marginRight: getPixel(1),
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: getPixel(4),
    },
    detailName: {
        color: '#999',
        paddingTop: getPixel(10),
        fontSize: getPixel(14),
    },
    detailNum: {
        color: '#000',
        fontSize: getPixel(16),
    },
    header: {
        height: getPixel(50),
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
        flexDirection: 'row',
    },
    statistics: {
        width: getScreenWidth() / 2,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
    },
    buttonGroup: {
        flexDirection: 'row',
        paddingLeft: getPixel(15),
        paddingRight: getPixel(15),
        height: getPixel(60),
        backgroundColor: '#FFF',
        width: getScreenWidth(),
        alignItems: 'center',
        elevation: 4,
        shadowOffset: { width: 0, height: 5 },
        shadowOpacity: 0.5,
        shadowRadius: 10,
        shadowColor: '#DDD',
        backgroundColor: '#FFF',
    },
    buttonDel: {
        backgroundColor: '#FF6B81',
        height: getPixel(40),
        borderTopLeftRadius: getPixel(10),
        borderBottomLeftRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
    buttonAdd: {
        backgroundColor: '#4a69dd',
        height: getPixel(40),
        borderTopRightRadius: getPixel(10),
        borderBottomRightRadius: getPixel(10),
        width: (getScreenWidth() - 30) / 2,
    },
});